﻿#region

using System;
using System.Linq;
using System.Web.Mvc;

#endregion

namespace CuongHanh.Security
{
    public class CustomAuthorizeContext
    {
        public static CustomAuthorizeContext Singleton = new CustomAuthorizeContext();

        public bool IsAuthorized(AuthorizationContext filterContext)
        {
            string userName = (filterContext.HttpContext.User != null)
                    ? filterContext.HttpContext.User.Identity.Name
                    : "";
            return !string.IsNullOrEmpty(userName);
        }

        private CustomAuthorizeAttribute GetCustomAuthorizeFromAction(AuthorizationContext filterContext)
        {
            CustomAuthorizeAttribute attr = filterContext.ActionDescriptor.GetCustomAttributes(typeof (CustomAuthorizeAttribute),
                    true).FirstOrDefault() as CustomAuthorizeAttribute;
            return attr;
        }

        private CustomAuthorizeAttribute GetCustomAuthorizeFromController(AuthorizationContext filterContext)
        {
            ControllerBase controller = filterContext.Controller;
            if(controller != null)
            {
                Type type = controller.GetType();
                CustomAuthorizeAttribute attr = type.GetCustomAttributes(typeof (CustomAuthorizeAttribute),
                        true).FirstOrDefault() as CustomAuthorizeAttribute;
                return attr;
            }
            return null;
        }
    }
}
